package org.zpmis.api.business;

import org.zpmis.common.base.AdminLoginUser;
import org.zpmis.common.base.BaseWebService;
import org.zpmis.common.enums.SequenceEnum;
import org.zpmis.common.exception.BusinessException;
import org.zpmis.common.result.ResultCode;
import org.zpmis.common.utils.StringUtil;
import org.zpmis.domain.order.enums.OrderDetailEnum;
import org.zpmis.domain.order.model.OrderDetail;
import org.zpmis.domain.order.qo.*;
import org.zpmis.domain.order.service.OrderDetailService;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.zpmis.domain.order.vo.OrderDetailVo;
import org.zpmis.domain.sequence.service.SequenceService;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created with CodeGenerator
 * Description: 订单明细业务处理
 * @author  Yang
 * Date: 2021-8-11
 * Time: 14:03:34
 */
@Service
@Slf4j
public class OrderDetailWebService extends BaseWebService {
    @Reference
    private OrderDetailService orderDetailService;

    @Reference
    private SequenceService sequenceService;

    /**
     * 新增订单明细
     * @param orderDetailQo
     * @throws Exception
     */
    public void addOrderDetail(AddOrderDetailQo orderDetailQo) throws Exception{
        orderDetailService.save(
        OrderDetail.builder()
                .orderId(orderDetailQo.getOrderId())
                .detailNum(sequenceService.getSequenceNum(SequenceEnum.ORDER_DETAIL))
                .collectionAmount(StringUtil.isEmpty(orderDetailQo.getCollectionAmount()) ? BigDecimal.ZERO : new BigDecimal(orderDetailQo.getCollectionAmount()).setScale(4))
                .collection(orderDetailQo.getCollection())
                .collectionTime(orderDetailQo.getCollectionTime())
                .createTime(Instant.now().toEpochMilli())
                .updateTime(Instant.now().toEpochMilli())
                .remark(orderDetailQo.getRemark())
                .collectionStatus(OrderDetailEnum.UNCOLLECTED_STATUS.code())
                .isDeleted(OrderDetailEnum.NOT_DELETE.code())
                .build()
        );
    }

    /**
     * 修改订单明细
     * @param editOrderDetailQo
     * @throws Exception
     */
    public void editOrderDetail(EditOrderDetailQo editOrderDetailQo) throws BusinessException,Exception {
        OrderDetail orderDetail = orderDetailService.findById(editOrderDetailQo.getId());
        if(orderDetail == null){
            throw new BusinessException(ResultCode.DATA_NOT_FOUND);
        }
        if(orderDetail.getCollectionStatus() == OrderDetailEnum.RECEIVED_STATUS.code()){
            throw new BusinessException(ResultCode.ORDER_DETAIL_NOT_EDIT);
        }
        orderDetailService.update(
                OrderDetail.builder()
                        .id(editOrderDetailQo.getId())
                        .collectionAmount(StringUtil.isEmpty(editOrderDetailQo.getCollectionAmount()) ? BigDecimal.ZERO : new BigDecimal(editOrderDetailQo.getCollectionAmount()).setScale(4))
                        .collection(editOrderDetailQo.getCollection())
                        .collectionTime(editOrderDetailQo.getCollectionTime())
                        .updateTime(Instant.now().toEpochMilli())
                        .remark(editOrderDetailQo.getRemark())
                        .collectionStatus(editOrderDetailQo.getCollectionStatus())
                        .build()
        );
    }

    /**
     * 删除订单明细
     * @param delOrderDetailQo
     * @throws BusinessException
     * @throws Exception
     */
    public void delOrderDetail(DelOrderDetailQo delOrderDetailQo) throws BusinessException,Exception {
        OrderDetail orderDetail = orderDetailService.findById(delOrderDetailQo.getId());
        if(orderDetail == null){
            throw new BusinessException(ResultCode.DATA_NOT_FOUND);
        }
        if(orderDetail.getCollectionStatus() == OrderDetailEnum.RECEIVED_STATUS.code()){
            throw new BusinessException(ResultCode.ORDER_DETAIL_NOT_DELETED);
        }
        orderDetailService.update(
                OrderDetail.builder()
                        .id(delOrderDetailQo.getId())
                        .isDeleted(OrderDetailEnum.DELETED.code())
                        .updateTime(Instant.now().toEpochMilli())
                        .build()
        );

    }

    /**
     * 根据订单id查询订单明细列表
     * @param orderDetailListQo
     * @return
     * @throws BusinessException
     * @throws Exception
     */
    public List<OrderDetailVo> orderDetailList(OrderDetailListQo orderDetailListQo)  throws BusinessException,Exception{
        Long orderId = orderDetailListQo.getOrderId();
        Condition condition = new Condition(OrderDetail.class);
        Example.Criteria criteria = condition.createCriteria();
        criteria.andEqualTo("orderId",orderId);
        criteria.andEqualTo("isDeleted",OrderDetailEnum.NOT_DELETE.code());
        condition.orderBy("createTime").desc();
        List<OrderDetail> orderDetailList = orderDetailService.findByCondition(condition);
        if(orderDetailList.isEmpty()){
            return new ArrayList<>();
        }
        List<OrderDetailVo> orderDetailVoList = orderDetailList.stream().map(OrderDetailVo::new).collect(Collectors.toList());
        return orderDetailVoList;
    }

    /**
     * 订单明细确认收款
     * @param confirmReceiptDetailQo
     * @throws BusinessException
     * @throws Exception
     */
    public void confirmCollection(ConfirmReceiptDetailQo confirmReceiptDetailQo) throws BusinessException,Exception{
        //获取当前登录用户
        AdminLoginUser adminLoginUser = super.getAdminLoginUser();
        if(adminLoginUser == null){
            throw new BusinessException(ResultCode.USER_NOT_LOGIN);
        }
        Long id = confirmReceiptDetailQo.getId();
        OrderDetail orderDetail = orderDetailService.findById(id);
        if(orderDetail == null || orderDetail.getIsDeleted() == OrderDetailEnum.DELETED.code()){
            throw new BusinessException(ResultCode.DATA_NOT_FOUND);
        }
        if(orderDetail.getCollectionStatus() == OrderDetailEnum.RECEIVED_STATUS.code()){
            throw new BusinessException(ResultCode.ORDER_DETAIL_COLLECTION);
        }
        //修改订单明细状态为已收款
        orderDetailService.update(
                OrderDetail.builder()
                .id(id)
                .collection(adminLoginUser.getName())
                .collectionTime(confirmReceiptDetailQo.getCollectionTime())
                .collectionStatus(OrderDetailEnum.RECEIVED_STATUS.code())
                .updateTime(Instant.now().toEpochMilli())
                .build()
        );

    }
}
